package cn.manjuu.touhou.engine;

import cn.manjuu.touhou.APP;
import cn.manjuu.touhou.util.Looger;
import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;

/**
 * 用来统一管理声音的播放
 * 
 * @author 宋疆疆
 */
public class SoundEngine {

	private static SoundEngine mInstance;
	private Context mContext;

	private MediaPlayer bgmMp;

	public void setContext(Context mContext) {
		this.mContext = mContext;
	}

	public static SoundEngine getInstance() {
		if (null == mInstance) {
			mInstance = new SoundEngine();
		}
		return mInstance;
	}

	private SoundEngine() {
		super();
	}

	public void playBGM(int rawId) {
		if (bgmMp != null) {
			stopBGM();
		}
		Looger.i(APP.SoundEngine, "Id" + rawId);
		bgmMp = MediaPlayer.create(mContext, rawId);
		bgmMp.start();
		BGMOnCompletionListener listener = new BGMOnCompletionListener();
		bgmMp.setOnCompletionListener(listener);
	}

	public void playEffect(int rawId) {
		MediaPlayer mp = MediaPlayer.create(mContext, rawId);
		mp.start();
	}

	public void restartBGM() {
		if (bgmMp != null) {
			bgmMp.start();
		}
	}

	public void pauseBGM() {
		// TODO Auto-generated method stub
		if (bgmMp != null) {
			bgmMp.pause();
		}
	}

	public void stopBGM() {
		if (bgmMp != null) {
			bgmMp.release();
			bgmMp = null;
		}
	}

	private class BGMOnCompletionListener implements OnCompletionListener {

		@Override
		public void onCompletion(MediaPlayer mp) {
			// TODO Auto-generated method stub
			bgmMp.start();
		}

	}

	private class MyOnPreparedListener implements OnPreparedListener {

		public void onPrepared(MediaPlayer mp) {
			mp.start();
		}

	}

}
